package com.bss.dao;


import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.*;
import java.sql.*;


public class DatabaseConnector {
	
	/**
	 * InitialContext variable
	 */
	private static Context initCtx = null;
	
	/**
	 * DatabaseConnector variable
	 */
	private static DatabaseConnector dbConnector;
	
	/**
	 * DataSource variable
	 */
    private static DataSource ds = null;
    
    /**
     * Connection variable
     */
    private Connection conn = null;
	
    /**
     * Constructor for getting the datasource after look up
     * @throws NamingException
     */
	private DatabaseConnector() throws NamingException {
		Object obj = null;
		try {
			//get the initial context
	        initCtx = new InitialContext();
	        
	        //look up for the database
	        obj = initCtx.lookup("java:comp/env/jdbc/TestDB");
	        
	        // get the data source
	        ds = (DataSource) obj;
		}
	    catch (NamingException namex)   {
	            throw namex;
	    }		
	}
	
	/**
	 * method to get the instance of the DatabaseConnector
	 * @return DatabaseConnector object
	 * @throws NamingException
	 */
	public static DatabaseConnector getInstance() throws NamingException {
		if(dbConnector== null)
				dbConnector = new DatabaseConnector();
		return dbConnector;
	}	
	
	/**
	 * method to get the connection
	 * @return Connection object
	 * @throws SQLException
	 */
	public Connection getConnection() throws SQLException {		
		try{
			//if datasource not null
			com.bss.framework.FrontController.trace("DataSource"+ds);
			if(ds!=null)
				
				//close connection
				conn= ds.getConnection();		
		}catch(SQLException ex)
		{
			throw ex;
			
		}
		return conn;
	}
}